<template>
  <div class="main">
    <h1>Experiment 2——Select Courses</h1>
    <p style="font-weight: bold">
      <span :style="{ color: pointR >= requiredPoint ? 'green' : 'red' }">
        {{ pointR }}
      </span>
      /{{ requiredPoint }}
    </p>
    <div class="course" id="all">
      <template v-for="(c, index) of coursesR" :key="index">
        <label>
          <input type="checkbox" v-model="courseSelectsR" :value="c" />
          {{ c.name }} - {{ c.point }} ({{ c.term }})
        </label>
        <br />
      </template>
    </div>
    <div
      class="course"
      id="select"
      :style="{
        border:
          pointR !== 0 ? (pointR >= requiredPoint ? '1px solid green' : '1px solid red') : 'none'
      }">
      <template v-for="(c, index) of courseSelectsR" :key="index">
        {{ c.name }} - {{ c.point }} ({{ c.term }})
        <br />
      </template>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { listCourses, type Course } from './service'
import { ref, watch } from 'vue'

const pointR = ref(0) // 响应式已选学分
const requiredPoint = 12 //学分条件
const cs = listCourses().sort((a, b) => a.term - b.term) //响应式课程列表，从 listCourses 函数获取并按学期排序。
const coursesR = ref<Course[]>(cs) // 所有课程，默认值为所有课程
const courseSelectsR = ref<Course[]>([]) // 已选课程，默认为空，与复选框双向绑定
//监听已选课程的改变
watch(courseSelectsR, () => {
  let count = 0
  courseSelectsR.value.forEach((c) => {
    count = count + c.point
  })
  pointR.value = count
  courseSelectsR.value.sort((a, b) => a.term - b.term) //按学期排序
})
</script>
<style scoped>
.main {
  border: 1px solid black;
}
.course {
  padding: 5px;
  display: inline-block;
  vertical-align: top;
}
#all {
  border: 1px solid red;
}
</style>
